import { createApp } from 'vue'
import { createPinia } from 'pinia'
import router from './router'
import App from './App.vue'

// Capacitor imports
import { Capacitor } from '@capacitor/core'
import { StatusBar, Style } from '@capacitor/status-bar'
import { SplashScreen } from '@capacitor/splash-screen'
import { Keyboard } from '@capacitor/keyboard'
import { App as CapApp } from '@capacitor/app'

// 浏览器兼容性检测已移除

// 导入登录页面检测工具
import { initLoginPageDetection } from './utils/loginPageDetector'

// 导入企业微信工具
import { isWeChatWork } from './utils/wechat'

// 导入Bootstrap CSS和JS
import 'bootstrap/dist/css/bootstrap.min.css'
import 'bootstrap/dist/js/bootstrap.bundle.min.js'

// 导入Bootstrap Icons
import 'bootstrap-icons/font/bootstrap-icons.css'

// 导入自定义样式
import './styles/main.css'
import './styles/mobile.css'
import './assets/css/responsive.css'

// 导入vconsole调试工具
import './utils/vconsole'

// Capacitor平台初始化
const initializeCapacitor = async () => {
  if (Capacitor.isNativePlatform()) {
    console.log('运行在原生平台:', Capacitor.getPlatform())
    
    try {
      // 设置状态栏样式
      await StatusBar.setStyle({ style: Style.Dark })
      await StatusBar.setBackgroundColor({ color: '#667eea' })
      
      // 隐藏启动屏幕
      await SplashScreen.hide()
      
      // 键盘配置
      Keyboard.addListener('keyboardWillShow', () => {
        document.body.classList.add('keyboard-open')
      })
      
      Keyboard.addListener('keyboardWillHide', () => {
        document.body.classList.remove('keyboard-open')
      })
      
      // 应用状态监听
      CapApp.addListener('appStateChange', ({ isActive }) => {
        console.log('应用状态变化:', isActive ? '激活' : '后台')
      })
      
      // 返回按钮处理
      CapApp.addListener('backButton', ({ canGoBack }) => {
        if (!canGoBack) {
          CapApp.exitApp()
        } else {
          window.history.back()
        }
      })
      
    } catch (error) {
      console.error('Capacitor初始化错误:', error)
    }
  } else {
    console.log('运行在Web平台')
  }
}

// 浏览器兼容性检测功能已移除

// 企业微信环境初始化（仅检测环境）
const initializeWeChatWork = async () => {
  if (isWeChatWork()) {
    console.log('检测到企业微信环境')
  } else {
    console.log('非企业微信环境')
  }
}

// 初始化登录页面检测
initLoginPageDetection()

// 创建应用实例
const app = createApp(App)
const pinia = createPinia()

app.use(pinia)
app.use(router)

// 添加错误处理
app.config.errorHandler = (err, instance, info) => {
  console.error('Vue应用错误:', err, info)
  handleCompatibilityError(err, () => {
    // 重试逻辑：重新挂载应用
    app.mount('#app')
  })
}

// 初始化应用
const initApp = async () => {
  try {
    // 初始化Capacitor
    await initializeCapacitor()
    
    // 初始化企业微信环境
    await initializeWeChatWork()
    
    // 挂载应用
    app.mount('#app')
    
    console.log('应用初始化完成')
  } catch (error) {
    console.error('应用初始化失败:', error)
    // 延迟重试
    setTimeout(() => {
      app.mount('#app')
    }, 2000)
  }
}

// 启动应用
initApp()